from django import http
from django.shortcuts import render
from django.views import View

from area.models import Area


class AreasView(View):
    def get(self, request):
        """ 获取省份数据返回结构
        {
            "code": "0",
            "errmsg": "OK",
            "province_list": [
                {
                    "id": 110000,
                    "name": "北京市"
                },
                {
                    "id": 120000,
                    "name": "天津市"
                },
                {
                    "id": 130000,
                    "name": "河北省"
                },
                ......
            ]
        }
        """
        """ 获取 市和区的数据返回结构
        {
            "code": "0",
            "errmsg": "OK",
            "sub_data": {
                "id": 130000,
                "name": "河北省",
                "subs": [
                    {
                        "id": 130100,
                        "name": "石家庄市"
                    },
                    ......
                ]
            }
        }"""

        # 1, 获取参数
        area_id = request.GET.get('area_id')

        # 2, 校验参数
        pass

        # 3, 取数据
        if area_id:
            # 取市或区的数据
            the_area = Area.objects.get(id=area_id)
            the_area_subs = the_area.subs.all()
            # 4, 构造数据
            sub_data = {
                "id": the_area.id,
                "name": the_area.name,
                "subs": []
            }
            for sub in the_area_subs:
                d = {
                    "id": sub.id,
                    "name": sub.name
                }
                sub_data['subs'].append(d)


            data = {
                "code": "0",
                "errmsg": "OK",
                "sub_data": sub_data
            }
            # 5, 返回响应
            return http.JsonResponse(data)
        else:
            # 取省的数据
            provinces = Area.objects.filter(parent__isnull=True)

            # 4, 格式化叔叔
            province_list = []
            for p in provinces:
                d = {
                    'id':p.id,
                    'name':p.name
                }
                province_list.append(d)

            data = {
                "code": "0",
                "errmsg": "OK",
                "province_list": province_list
            }

            # 5, 返回响应
            return http.JsonResponse(data)
